package com.qidian.connection.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;


public final class ConnectionPool 
{
//	private static Logger logger = Logger.getLogger(ConnectionPool.class);
	public static String dbconfigFile = "dbconfig.properties" ;
	private static BasicDataSource dataSource = null;
	
	static
	{
		init() ;
	}

	/**
	 * 初始化连接池。
	 */
	private static void init() 
	{
	    if (dataSource != null) 
	    {
	        try 
	        {
	            dataSource.close();
	        }
	        catch (Exception e) 
	        {
//	        	logger.error(e.getMessage(), e);
	        	e.printStackTrace() ;
	        }
	        dataSource = null;
	    }

	    try 
	    {
	    	ClassLoader loader = ConnectionPool.class.getClassLoader() ;
//	    	loader.getResource("").getPath() ;
	    	String configFilePath = loader.getResource("").getPath()+dbconfigFile ;
	    	configFilePath = java.net.URLDecoder.decode(configFilePath) ;
	    	InputStream configInputStream = new FileInputStream(new File(configFilePath)); 
	    	//InputStream configInputStream = ClassLoader.getSystemResourceAsStream(configFilePath) ;
	    	Properties p = new Properties();
	    	p.load(configInputStream) ;
	    	configInputStream.close() ;
            p.setProperty("testOnBorrow", "true");
	        dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);
	        System.out.println("Connection Pool initialized successfully!");
	    }
	    catch (Exception e) 
	    {
//	    	logger.error(e.getMessage(), e);
	    	e.printStackTrace() ;
	    	System.exit(-1);
        }
	    
    }

	/**
	 * 从连接池获取连接。
	 * 
	 * @return connection
	 * @throws SQLException
	 */
    public static synchronized Connection getConnection() throws SQLException 
    {
        Connection conn = null;
        if (dataSource != null)
            conn = dataSource.getConnection();
        return conn;
    }
    
    /**
     * 释放数据库连接。
     * 
     * @param conn
     */
    public static synchronized void freeConn(Connection conn)
    {
    	try
    	{
    		if(conn != null)
    		{
    			conn.clearWarnings() ;
				conn.close();
				conn = null;
			}
    	}
    	catch(Exception e)
    	{
    		e.printStackTrace() ;
    	}
    }
}
